class LoginController < ApplicationController
 
 
  def index
    require 'open-uri'
    
    
    if session[:ticket_id] = request.params[:ticketid]

          @xml = URI.parse("https://webapps.unibe.ch/a3ublogin2/a3ubauthorization?ticketid=" + session[:ticket_id]).read  
          #@xml = URI.parse("http://ethikreview.dreamhosters.com/sample.xml").read  
          @data = Hash.from_xml(@xml)
          @data = @data["a3ubloginresponse"]["ch.unibe.id.se.beans.authorization_bean__v03"]
          session[:ticket] = @data
          @a3ubid = @data["user_identifier_number"]
          @user = User.find(:first, :conditions => { :a3ubid => @a3ubid })
          if @user.nil?
            @user = User.new
          end
              
          #aktualisiere daten
          #@user.a3ubid = @a3ubid
          #@user.name = @data["given_name"] + " " + @data["sur_name"]
          #@user.email = @data["email_address"]

          #@user.save
          
          session[:user_id] = @user.id
          

          redirect_to "/login/role"
          
    elsif session[:ticket_id].nil? and ENV['RAILS_ENV'] == "development"
      session[:user_id] = 1
      @user = User.find(1)
      @user.role = "admin"
      @user.save
      flash[:error] = "Login als Testadmin #{@user.id}"
      redirect_to "/admin"
    else
      flash[:error] = "Problem beim Einloggen"
      redirect_to "/submit/start"
    end
    
          
  end
  
  def role
    @user = User.find(session[:user_id])    
    #refactor this out, user _ manaagment is nicer to do within the app, also for alter extendability
    #@user.role = session[:ticket]['unibe_appl_authorization_map']['entry']['map']['entry']['list']['string'] 
    @user.save
    redirect_to "/login/route"
    
  
  rescue NoMethodError
    flash[:error] = "nomethoderror"
    redirect_to "/login/route"
  
  end
  
  def route
    @user = User.find(session[:user_id])    
    if @user.role == "admin"
      flash[:notice] = "Login erfolgreich"
      redirect_to "/admin/"
    elsif @user.role == "reviewer"
      flash[:notice] = "Login erfolgreich"
      redirect_to "/review/"
    else
      flash[:error] = "Sie haben keine Zugriffsrecht: Bitte beim Administrator melden."
      session[:user_id] = nil
      redirect_to "/submit/start"        
    end
    
  end  
  
end
